package com.wanhe.base.util;

import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class WStringUtils {

    public static String ENCODING = "utf-8";
    private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();

    public static boolean isEmpty(String str) {
        return (null==str || str.isEmpty());
    }

    public static String getUnixTimeStamp() {
        return String.valueOf(System.currentTimeMillis()/1000);
    }

    public static boolean isPhoneNumber(String str) {
        boolean result = false;
        Pattern p = Pattern.compile("[1]{1}[0-9]{10}");
        Matcher m = p.matcher(str);
        result = m.matches();
        return result;
    }


    public static boolean isPassword(String str) {
        boolean result = false;
        Pattern p = Pattern.compile("[A-Za-z0-9]{6,12}");
        Matcher m = p.matcher(str);
        result = m.matches();
        return result;
    }

    public static boolean isEmail(String str) {
        boolean result = false;
        Pattern p = Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");
        Matcher m = p.matcher(str);
        result = m.matches();
        return result;
    }

    public static boolean isNickName(String str) {
        boolean result = false;
        Pattern p1 = Pattern.compile("[\\u4e00-\\u9fa5 a-zA-Z0-9]{1,10}");  //1-8个汉字、数字、字母、空格
        Matcher m1 = p1.matcher(str);
        result = m1.matches();
        return result;
    }

	/**
	 * 去除部分手机获取到的WIFI的SSID带有前后“”
	 * @param ssid
	 * @return
	 */
    public static String getSSID(String ssid){
    	if(ssid.length() > 2 && ssid.substring(0, 1).equals("\"") && ssid.substring(ssid.length() - 1, ssid.length()).equals("\"")){
			ssid = ssid.substring(1, ssid.length() - 1);
		}
		return ssid;
    }
    
    public static String hmacSHA1Encrypt(String encryptKey, String encryptText)
            throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        return new String(base64Encode(mac.doFinal(text)).getBytes(ENCODING));
    }

    public static String base64Encode(byte[] data) {
        int start = 0;
        int len = data.length;
        StringBuffer buf = new StringBuffer(data.length * 3 / 2);

        int end = len - 3;
        int i = start;
        int n = 0;

        while (i <= end) {
            int d = (((data[i]) & 0x0ff) << 16) | (((data[i + 1]) & 0x0ff) << 8) | ((data[i + 2]) & 0x0ff);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append(legalChars[d & 63]);

            i += 3;

            if (n++ >= 14) {
                n = 0;
                buf.append(" ");
            }
        }

        if (i == start + len - 2) {
            int d = (((data[i]) & 0x0ff) << 16) | (((data[i + 1]) & 255) << 8);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append("=");
        } else if (i == start + len - 1) {
            int d = ((data[i]) & 0x0ff) << 16;

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append("==");
        }

        return buf.toString();
    }

    public static String md5(String plainText) {
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {

            Logger.d("RequestHead!!", e.getMessage());
            e.printStackTrace();
            return null;
        }
        return buf.toString();
    }
    public static String md5(byte[] plainText) {
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText);
            byte b[] = md.digest();
            int i;
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return buf.toString();
    }
    
    public static String md5(ByteBuffer plainText) {
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText);
            byte b[] = md.digest();
            int i;
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        return buf.toString();
    }
    /**
     * 转换时间表达式
     * @param millis 时间戳
     * @param patten 时间表达式
     * @return
     */
    public static String GetStringFromLong(long millis, String patten) {
		SimpleDateFormat sdf = new SimpleDateFormat(patten, Locale.US);
		Date dt = new Date(millis);
		return sdf.format(dt);
	}

    /**
     * 获取给定偏移时间
     * @param format 时间表达式
     * @param dd 偏移天数
     * @return
     */
    public static String getDateFrontOrOfter(String format, int dd){
    	SimpleDateFormat Dataformat = new SimpleDateFormat(format, Locale.US);
    	Calendar nowData = Calendar.getInstance();
    	nowData.add(Calendar.DAY_OF_MONTH, dd);
    	return Dataformat.format(nowData.getTime());
    }
    
    /**
     * 转换时间表达式
     * @param mDate 源时间表达式
     * @param inFormat 输入时间表达式
     * @param outFormat 输出时间表达式
     * @return
     */
    public static String changeTimeFormat(String mDate, String inFormat, String outFormat){
		SimpleDateFormat df = new SimpleDateFormat(inFormat, Locale.US);
		SimpleDateFormat df1 = new SimpleDateFormat(outFormat, Locale.US);
		String date =null;
		try {
			Date d= df.parse(mDate);
		    date = df1.format(d);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
    }
    
    /**
     * 判断传入时间对应的星期几
     * @param date 时间
     * @param inFormat 时间的格式
     * @return
     */
    public static String getWeekofDay(String date, String inFormat){
    	final String[] WEEKDAYS = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
    	SimpleDateFormat df = new SimpleDateFormat(inFormat, Locale.US);
    	Date dt;
		try {
			dt = df.parse(date);
			Calendar cal = Calendar.getInstance();
	        cal.setTime(dt);
	        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
	        if (w < 0)
	            w = 0;
	        return WEEKDAYS[w];
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
    }
}
